<template>
  <div class="errand-container">
    <h1>跑腿代办</h1>
    <!-- 选项卡切换 -->
    <div class="tabs">
      <button :class="{ 'active': currentTab === 'orders' }" @click="switchTab('orders')">订单</button>
      <button :class="{ 'active': currentTab === 'runners' }" @click="switchTab('runners')">跑腿员</button>
    </div>

    <!-- 订单列表 -->
    <div v-if="currentTab === 'orders'" class="orders-list">
      <div class="filter-bar">
        <input type="text" v-model="searchKeyword" placeholder="搜索订单..." @input="debounceSearch">
        <select v-model="orderFilter" @change="fetchOrders">
          <option value="">全部订单</option>
          <option value="pending">待接单</option>
          <option value="accepted">已接单</option>
          <option value="processing">进行中</option>
          <option value="completed">已完成</option>
          <option value="cancelled">已取消</option>
        </select>
      </div>
      <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
      <div v-if="isLoading" class="loading">加载中...</div>
      <div class="order-cards">
        <div v-for="order in orders" :key="order.id" class="order-card" @click="goToOrderDetail(order.id)">
          <div class="order-info">
            <h3>{{ order.title }}</h3>
            <p class="order-type">{{ typeMap[order.type] }}</p>
            <div class="order-locations">
              <p><i class="icon-pickup"></i> {{ order.pickup_location }}</p>
              <p><i class="icon-delivery"></i> {{ order.delivery_location }}</p>
            </div>
            <p class="order-price">¥{{ order.price }}</p>
            <div class="order-status" :class="order.status">
              {{ statusMap[order.status] }}
            </div>
          </div>
        </div>
      </div>
      <button class="create-order-btn" @click="goToCreateOrder()">发布订单</button>
    </div>

    <!-- 跑腿员列表 -->
    <div v-else class="runners-list">
      <div class="filter-bar">
        <input type="text" v-model="searchKeyword" placeholder="搜索跑腿员..." @input="debounceSearch">
      </div>
      <div class="runner-cards">
        <div v-for="runner in runners" :key="runner.id" class="runner-card" @click="goToRunnerDetail(runner.id)">
          <img :src="runner.avatar || '/default-avatar.png'" alt="跑腿员头像">
          <div class="runner-info">
            <h3>{{ runner.username }}</h3>
            <div class="runner-rating">
              <div class="stars">
                <i v-for="i in 5" :key="i" :class="{ 'filled': i <= runner.rating }" class="fa-star"></i>
              </div>
              <span>{{ runner.rating }}</span>
            </div>
            <p class="runner-completed">{{ runner.completed_orders }} 单已完成</p>
            <p class="runner-type">可接: {{ runner.accepted_types.map(t => typeMap[t]).join(', ') }}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { errandApi } from '@/api'
import { formatDate } from '@/utils/date'
import { debounce } from 'lodash'

const router = useRouter()
const currentTab = ref('orders') // 'orders' 或 'runners'
const orders = ref([])
const runners = ref([])
const searchKeyword = ref('')
const orderFilter = ref('')

// 订单类型映射
const typeMap = {
  'food': '外卖代拿',
  'express': '快递代取',
  'other': '其他代办'
}

// 订单状态映射
const statusMap = {
  'pending': '待接单',
  'accepted': '已接单',
  'processing': '进行中',
  'completed': '已完成',
  'cancelled': '已取消'
}

// 切换选项卡
const switchTab = (tab) => {
  currentTab.value = tab
  if (tab === 'orders') {
    fetchOrders()
  } else {
    fetchRunners()
  }
}

// 获取订单列表
const isLoading = ref(false)
const errorMessage = ref('')

const fetchOrders = async () => {
  isLoading.value = true
  errorMessage.value = ''
  try {
    const params = {
      search: searchKeyword.value,
      status: orderFilter.value
    }
    const res = await errandApi.getOrders(params)
    orders.value = res.data.results
  } catch (error) {
    errorMessage.value = '获取订单失败，请稍后重试'
    console.error('获取订单失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 获取跑腿员列表
const fetchRunners = async () => {
  isLoading.value = true
  errorMessage.value = ''
  try {
    const params = {
      search: searchKeyword.value
    }
    const res = await errandApi.getRunners(params)
    runners.value = res.data.results
  } catch (error) {
    errorMessage.value = '获取跑腿员失败，请稍后重试'
    console.error('获取跑腿员失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 防抖搜索
const debounceSearch = debounce(() => {
  if (currentTab.value === 'orders') {
    fetchOrders()
  } else {
    fetchRunners()
  }
}, 500)

// 跳转到订单详情
const goToOrderDetail = (orderId) => {
  router.push({ name: 'orderDetail', params: { id: orderId } })
}

// 跳转到跑腿员详情
const goToRunnerDetail = (runnerId) => {
  // 注意：这里没有对应的路由，根据实际需求添加
  console.log('查看跑腿员详情:', runnerId)
}

// 跳转到创建订单
const goToCreateOrder = () => {
  router.push({ name: 'createOrder' })
}

// 页面加载时执行
onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.errand-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.tabs {
  display: flex;
  margin-bottom: 20px;
}

.tabs button {
  padding: 10px 20px;
  background-color: #f0f0f0;
  border: none;
  cursor: pointer;
}

.tabs button.active {
  background-color: #42b983;
  color: white;
}

.filter-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.filter-bar input,
.filter-bar select {
  padding: 8px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}

.order-cards,
.runner-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.order-card,
.runner-card {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: box-shadow 0.3s;
}

.order-card:hover,
.runner-card:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.runner-card {
  display: flex;
  gap: 16px;
}

.runner-card img {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
}

.order-info,
.runner-info {
  flex: 1;
}

.order-card h3,
.runner-card h3 {
  margin-bottom: 8px;
  font-size: 18px;
}

.order-type {
  color: #666;
  margin-bottom: 8px;
  font-size: 14px;
}

.order-locations {
  margin-bottom: 12px;
}

.order-locations p {
  font-size: 14px;
  margin-bottom: 4px;
  display: flex;
  align-items: center;
}

.icon-pickup,
.icon-delivery {
  margin-right: 6px;
  color: #42b983;
}

.order-price {
  font-size: 18px;
  font-weight: bold;
  color: #ff7a45;
  margin-bottom: 8px;
}

.order-status {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.order-status.pending {
  background-color: #f0f9eb;
  color: #67c23a;
}

.order-status.ongoing {
  background-color: #ecf5ff;
  color: #4096ff;
}

.order-status.completed {
  background-color: #f5f5f5;
  color: #909399;
}

.order-status.cancelled {
  background-color: #fef0f0;
  color: #f56c6c;
}

.runner-rating {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.stars {
  margin-right: 6px;
  color: #e6a23c;
}

.stars .filled {
  fill: #e6a23c;
}

.runner-completed,
.runner-type {
  color: #666;
  font-size: 14px;
  margin-bottom: 4px;
}

.create-order-btn {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #42b983;
  color: white;
  border: none;
  font-size: 24px;
  cursor: pointer;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}
</style>